import { FC, useState } from 'react';
import Taro from '@tarojs/taro';
import { View, Text, Image, ScrollView } from '@tarojs/components';
import { useLoad, useRouter } from '@tarojs/taro';
import apiRequest from '@/service/apiRequest';
import { IMG_URL } from '@/constants/api';

import './index.scss';

const PetIdentifyDetail: FC = () => {
  const router = useRouter();
  const { id } = router.params;
  const [petImage, setPetImage]= useState("");
  const [breedResults, setBreedResults]= useState([]);
  const [breedInfo, setBreedInfo]= useState<any>({});
  const [similarBreeds, setSimilarBreeds]= useState([]);


  // 模拟数据，实际应用中应从API获取或通过路由参数传递
  // const petImage = 'https://images.unsplash.com/photo-1552053831-71594a27632d';
  
  // const breedResults: BreedResult[] = [
  //   { name: '威尔士柯基犬（彭布罗克）', confidence: 98, confidenceLevel: 'high' },
  //   { name: '威尔士柯基犬（卡迪根）', confidence: 65, confidenceLevel: 'medium' },
  //   { name: '柴犬', confidence: 32, confidenceLevel: 'low' },
  // ];
  
  // const breedInfo: BreedInfo = {
  //   origin: '英国威尔士',
  //   size: '小型犬',
  //   lifespan: '12-15年',
  //   personality: '活泼、聪明、友善、勇敢',
  //   characteristics: ['短腿长身', '双层被毛', '警惕性高', '适应性强', '易训练'],
  // };
  
  // const similarBreeds: SimilarBreed[] = [
  //   { 
  //     name: '卡迪根威尔士柯基', 
  //     image: 'https://images.unsplash.com/photo-1537151608828-ea2b11777ee8', 
  //     similarity: 85 
  //   },
  //   { 
  //     name: '柴犬', 
  //     image: 'https://images.unsplash.com/photo-1562695530-7e8aa4d65321', 
  //     similarity: 62 
  //   },
  //   { 
  //     name: '杰克罗素梗', 
  //     image: 'https://images.unsplash.com/photo-1548199973-03cce0bbc87b', 
  //     similarity: 45 
  //   },
  // ];

  // 获取置信度等级对应的样式类名
  const getConfidenceLevelClass = (level: number) => {
    switch (level) {
      case 0:
        return 'high-confidence';
      case 1:
        return 'medium-confidence';
      default:
        return 'low-confidence';
    }
  };

  const requestDetails = async () => {
    let res = await apiRequest.get(`/api/pet_identifies/detail/${id}`);
    console.log(res);
    setPetImage(res.petImage);
    if (res.content) {
      res.content = JSON.parse(res.content);
      let breedResultsList = res.content ? res.content.map((item: any, index) => Object.assign({}, {name: item.name, confidence: item.score * 100, confidenceLevel: index})) : [];
      setBreedResults(breedResultsList);

      requestPetdetails(res.content[0].name);
  
      setSimilarBreeds(res.content.slice(1));
    }

  }

  const requestPetdetails = async (petName) => {
    let res = await apiRequest.get("/api/pet_encyclopedias/detail", {petName})
    if (res && res.length > 0) {
      let { nation, life, characters, easyOfDisease, name, feature, careKnowledge, feedPoints, desc, coverURL } = res[0];
        if (characters.includes('，')) {
          characters = characters.split('，');
        } else if (characters.includes('；')) {
          characters = characters.split('；');
        } else if (characters.includes(';')) {
          characters = characters.split(';');
        } else if (characters.includes(',')) {
          characters = characters.split(',');
        } else if (characters.includes('、')) {
          characters = characters.split('、');
        }

        setBreedInfo({
          nation,
          life,
          characters,
          easyOfDisease,
          petName: name,
          feature,
          careKnowledge,
          feedPoints,
          desc,
          coverURL
        });
        

    }
  }
  
  const breedInfoList = [
    {
      name: "体态特征",
      detail: breedInfo.feature
    },
    {
      name: "照顾须知",
      detail: breedInfo.careKnowledge
    },
    {
      name: "喂养注意",
      detail: breedInfo.feedPoints
    }
  ].filter(item => item.detail).map((item) => (
    <View className='breed-info-box result-card'>
      <View className='breed-info-c-title'>{ item.name }</View>
      <View className='breed-info-c-content'>{ item.detail }</View>
    </View>
  ))

  const handlePreviewImage = () => {
    Taro.previewMedia({
        sources: [{url: petImage}]
    })
  }

  useLoad(() => {
    requestDetails();
  })

  return (
    <View className='pet-identify-detail'>
        {/* 宠物图片 */}
        <View className='pet-image-container'>
          <Image src={petImage} className='pet-image' mode='aspectFill' onClick={handlePreviewImage} />
        </View>
        
        {/* 鉴定结果 */}
        <View className='result-card'>
          <View className='result-title'>
            {/* <AtIcon value='paw' size='18' color='#ff7a59' /> */}
            <Text>鉴定结果</Text>
          </View>
          
          {
            breedResults.length ? breedResults.map((result: any, index) => (
              <View key={index}>
                <View className='breed-result'>
                  <Text className='breed-name'>{result.name}</Text>
                  <Text className={`confidence ${getConfidenceLevelClass(result.confidenceLevel)}`}>
                    {result.confidence.toFixed(2)}%
                  </Text>
                </View>
                <View className='progress-bar'>
                  <View 
                    className='progress' 
                    style={{ width: `${result.confidence}%` }} 
                  />
                </View>
              </View>
            )) : null
          }
        </View>
        
        {/* 品种信息 */}
        {
          Object.keys(breedInfo).length ? (
            <View className='result-card'>
              <View className='result-title flex-b-c'>
                {/* <AtIcon value='info-circle' size='18' color='#ff7a59' /> */}
                <Text>品种信息</Text>
              </View>
              
              <View className='breed-info'>
                <View className='info-item'>
                  <Text className='info-label'>原产地</Text>
                  <Text className='info-value'>{breedInfo.nation}</Text>
                </View>
                {/* <View className='info-item'>
                  <Text className='info-label'>体型</Text>
                  <Text className='info-value'>{breedInfo.size}</Text>
                </View> */}
                <View className='info-item'>
                  <Text className='info-label'>寿命</Text>
                  <Text className='info-value'>{breedInfo.life}</Text>
                </View>
                <View className='info-item'>
                  <Text className='info-label'>特征</Text>
                  <View className='info-value'>
                    <View className='characteristic-tags'>
                      {
                        breedInfo.characters ? breedInfo.characters.map((tag, index) => (
                          <Text key={index} className='tag'>{tag}</Text>
                        )) : null
                      }
                    </View>
                  </View>
                </View>
                {
                  breedInfo.easyOfDisease ? (
                    <View className='info-item'>
                      <Text className='info-label'>健康提示</Text>
                      <Text className='info-value'>{breedInfo.easyOfDisease}</Text>
                    </View>
                  ) : null
                }
              </View>
            </View>
          ) : null
        }
        
        {/* 相似品种 */}
        <View className='result-card'>
          <View className='result-title'>
            {/* <AtIcon value='file-generic' size='18' color='#ff7a59' /> */}
            <Text>相似品种</Text>
          </View>
          
          <ScrollView className='similar-breeds' scrollX>
            {
              similarBreeds.length ? similarBreeds.map((breed: any, index) => (
                <View key={index} className='similar-breed-card'>
                  <Image 
                    src={breed.baike_info?.image_url || `${IMG_URL}/hos_fail_img.png`} 
                    className='similar-breed-image' 
                    mode='aspectFill' 
                  />
                  <Text className='similar-breed-name'>{breed.name}</Text>
                  <Text className='similarity'>相似度: {(breed.score * 100).toFixed(2)}%</Text>
                </View>
              )) : null
            }
          </ScrollView>
        </View>

        {/* 详细信息 */}
        {
          Object.keys(breedInfo).length? (
            <View>
              {
                breedInfoList
              }
              <View className='breed-info-box result-card'>
                <View className='breed-info-c-title'>简介</View>
                <View>
                  <Image src={breedInfo.coverURL} className='breed-info-c-img' mode='aspectFill' />
                </View>
                <View className='breed-info-c-content'>{ breedInfo.desc }</View>
              </View>
            </View>
          ) : null
        }
    </View>
  );
};

export default PetIdentifyDetail;